# coding=utf-8
from grid_feature import *
from tools import *


# 初步加工business数据，删除无用列，数据转换，统计counts，映射gird id
def business_step1(num, max_longitude, min_longitude, max_latitude, min_latitude, interval):
    data = pd.read_csv('./data/YunyingData.csv')
    data['GPSONTIME'] = pd.to_datetime(data['GPSONTIME'])
    data['GPSOUTTIME'] = pd.to_datetime(data['GPSOUTTIME'])
    drop_target = ['SIM', 'SANGLE', 'EANGLE', 'DISTANCE', 'MONEY', 'ONTIME', 'OUTTIME', 'OUTRUN',
           'WAITTIME', 'UNLOADDIST', 'INDATE', 'JJQBC']
    data = data.drop(drop_target, axis=1)
    data = data[data['SAVAIL'] == 'A']
    data = data[data['EAVAIL'] == 'A']

    # 经纬度字符转浮点
    for col_name in ['SJD', 'SWD', 'EJD', 'EWD']:
       int_to_float(data, col_name)

    # 经纬度异常删除
    data = data[(data['SJD'] <= max_longitude) & (data['SJD'] >= min_longitude) &
                (data['SWD'] <= max_latitude) & (data['SWD'] >= min_latitude) &
                (data['EJD'] <= max_longitude) & (data['EJD'] >= min_longitude) &
                (data['EWD'] <= max_latitude) & (data['EWD'] >= min_latitude)]

    # 时间相关属性
    data['time_chunk'] = data['GPSONTIME'].map(lambda x: (x.hour*60+x.minute)//interval+1)
    data['month_day'] = data['GPSONTIME'].map(lambda x: x.day)
    data['hour'] = data['GPSONTIME'].map(lambda x: x.hour)
    data['week_day'] = data['GPSONTIME'].map(lambda x: x.weekday())

    # 格子id
    data['grid_id'] = map_grid(data['SJD'], data['SWD'], num, max_longitude, min_longitude, max_latitude, min_latitude)

    data.drop(['SAVAIL', 'EAVAIL'], axis=1, inplace=True)

    data_counts = data.groupby(['month_day', 'week_day', 'hour', 'time_chunk', 'grid_id']).size().rename('counts').reset_index()

    data_counts.to_csv('./data/'+str(num)+'_'+str(interval)+'business_step1.csv', index=False)


# 填充时间序列，添加新的属性，形成最终的business特征
def business_step2(num, interval, month_length, time_chunk_size):
    data = pd.read_csv('./data/'+str(num)+'_'+str(interval)+'business_step1.csv')

    # 有发生过叫车行为的格子
    target_grid_id = data['grid_id'].unique()

    # 标准化
    scalar = max(data['counts']) - min(data['counts'])
    data['counts'] = (data['counts'] - min(data['counts']))/scalar

    # 对于某些时段没有叫车的数据的填充
    month_day = pd.DataFrame([[i+1, 0] for i in range(month_length)], columns=['month_day', 'key'])
    time_chunk = pd.DataFrame([[i+1, 0] for i in range(24*60//interval)], columns=['time_chunk', 'key'])
    grid_id = pd.DataFrame([[i+1, 0] for i in range(num*num) if i+1 in target_grid_id], columns=['grid_id', 'key'])

    all_data = pd.merge(month_day, time_chunk, how='outer')
    all_data = pd.merge(all_data, grid_id, how='outer')
    all_data = all_data.drop('key', axis=1)

    all_data = pd.merge(all_data, data, how='left')
    all_data = all_data.fillna(0)

    # 添加历史平均数据
    all_data['total_time_chunk'] = (all_data['month_day'] - 1) * 24 * (60/interval) + all_data['time_chunk']
    temp = all_data[['grid_id', 'total_time_chunk', 'counts']]
    temp_avg = temp.groupby(['grid_id', 'total_time_chunk']).sum().groupby(['grid_id']).cumsum().reset_index()
    temp_avg['avg_counts'] = temp_avg['counts'] / temp_avg['total_time_chunk']
    temp_avg.drop(['counts'], axis=1, inplace=True)
    all_data = pd.merge(all_data, temp_avg, on=['grid_id', 'total_time_chunk'])
    all_data.drop(['total_time_chunk'], axis=1, inplace=True)

    # 获得前time_chunk_size时间块的订单数据
    final_data = []
    for grid_id in target_grid_id:
        temp = all_data[all_data['grid_id'] == grid_id]
        target = temp[time_chunk_size:].copy()
        for i in range(1, time_chunk_size+1):
            target['last'+str(i)] = list(temp[time_chunk_size-i:-i]['counts'])
        final_data.append(target)

    final_data = pd.concat(final_data)
    final_data.to_csv('./data/'+str(num)+'_'+str(interval)+'business_final.csv', index=False)
